import axios from "axios";
import { Message, MessageBox } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import Qs from "qs";

const needToken = ["/user", "/appointActivity"];

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 20000 // request timeout
  // headers: { "Content-Type": "application/x-www-form-urlencoded" },
  // headers: { "X-Requested-With": "XMLHttpRequest" }
  // headers: {
  //   "access-control-allow-origin": "*"
  // }
  // transformRequest: [
  //   function(data) {
  //     data = Qs.stringify(data);
  //     return data;
  //   }
  // ] //序列化参数
});

// request interceptor
service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers["Changbo-Token"] = getToken(); // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // }
    if (config.method == "get") {
      if (config.hasOwnProperty("params")) {
        config.params.noCatch = Date.parse(new Date());
      } else {
        config.params = {
          noCatch: Date.parse(new Date())
        };
      }
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// respone interceptor
service.interceptors.response.use(
  // response => response.data,
  /**
   * 下面的注释为通过response自定义flag来标示请求状态，当flag返回如下情况为权限有问题，登出并返回到登录页
   * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
   */
  response => {
    const res = response.data;
    if (res.flag != 1) {
      // Message({
      //   message: res.msg,
      //   type: "error",
      //   duration: 5 * 1000,
      //   showClose: true
      // });
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (res.flag == 0) {
        MessageBox.confirm("您还未登录，或者已被登出，请重新登录", "请登录", {
          confirmButtonText: "登录",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // store.dispatch("ToggleLoginDialog", true).then(() => {
          //   location.reload(); // 为了重新实例化vue-router对象 避免bug
          // });
          store.dispatch("ToggleLoginDialog", true);
        });
      } else if (res.flag == -1) {
        return response.data;
      }
      return Promise.reject("error");
    } else {
      return response.data;
    }
    // return response.data;
  },

  error => {
    console.log("err" + error); // for debug
    // Message({
    //   message: "服务器超时",
    //   type: "error",
    //   duration: 5 * 1000,
    //   showClose: true
    // });
    return Promise.reject(error);
  }
);

export default service;
